package com.lanlian.cayman.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.cayman.view.CitySelectorWindow;
import com.lanlian.cayman.view.ShowPictureDialog;
import com.lanlian.commonlib.base.BaseFragment;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.CityInfo;
import com.lanlian.commonlib.bean.PreRegisterExtendInfo;
import com.lanlian.commonlib.bean.PreRegisterInfo;
import com.lanlian.commonlib.bean.ProvinceInfo;
import com.lanlian.commonlib.bean.ReqLazyEnum;
import com.lanlian.commonlib.bean.ReqVerifyID;
import com.lanlian.commonlib.bean.RespLazyEnum;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.upyun.IUploadFileCallback;
import com.lanlian.commonlib.upyun.MUploadFile;
import com.lanlian.commonlib.upyun.UploadPic;
import com.lanlian.imagelib.ShowImageUtils;
import com.lanlian.uikit.ActionItem;
import com.lanlian.uikit.CustomBottomSheetDialog;
import com.lanlian.utillib.CommonUtils;
import com.lanlian.utillib.DateUtils;
import com.lanlian.utillib.IDCard;
import com.lanlian.utillib.ImageUtils;
import com.lanlian.utillib.WorksSizeCheckUtil;

import java.io.File;
import java.io.InputStream;

import static com.lanlian.cayman.activity.OpenAccentActivity.respPreRegister;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/14 14:18
 *     desc   : 注册开户第二步，个人信息
 *     version: 1.0
 * </pre>
 */
@SuppressLint("ValidFragment")
public class RegisterOneFragment extends BaseFragment implements View.OnClickListener {

    private EditText mEtName;
    private EditText mEtSurname;
    private EditText mEtIdCard;
    private RadioGroup mRgSex;
    private EditText mEtMail;
    private TextView mTvCity;
    private EditText mEtAddress;
    private ImageView mImgIdCardFront;
    private ImageView mImgIdCardBack;
    private TextView mTvNext;

    private OnNextClickListener mOnNextClickListener;

    private String mIdCardFrontStr;
    private String mIdCardBackStr;
    private boolean mIsEditHasContent;

    private CustomBottomSheetDialog mBottomSheetDialog;
    private CitySelectorWindow mCitySelectorWindow;

    public interface OnNextClickListener {
        void onNextClick();
    }

    public RegisterOneFragment(OnNextClickListener mOnNextClickListener) {
        this.mOnNextClickListener = mOnNextClickListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBottomSheetDialog = new CustomBottomSheetDialog(getActivity(), "请选择");
        mBottomSheetDialog.addAction(new ActionItem("拍照"));
        mBottomSheetDialog.addAction(new ActionItem("从相册中选取"));
        mBottomSheetDialog.setOnItemClickListener(new CustomBottomSheetDialog.OnItemOnClickListener() {
            @Override
            public void onItemClick(ActionItem item, int position) {
                switch (item.mTitle) {
                    case "拍照":
                        openSysCamera();
                        break;
                    case "从相册中选取":
                        openSysAlbum();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register_one, null);
        initView(view);
        setListeners();
        initData();
        LLApplication.reqUserRegister.setMale(1);
        return view;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mEtSurname = view.findViewById(R.id.et_surname);
        mEtName = view.findViewById(R.id.et_name);
        mEtIdCard = view.findViewById(R.id.et_id_card);
        mRgSex = view.findViewById(R.id.rg_sex);
        mEtMail = view.findViewById(R.id.et_mail);
        mTvCity = view.findViewById(R.id.tv_city);
        mEtAddress = view.findViewById(R.id.et_address);
        mImgIdCardFront = view.findViewById(R.id.img_id_card_front);
        mImgIdCardBack = view.findViewById(R.id.img_id_card_back);
        mTvNext = view.findViewById(R.id.tv_next);
        mCitySelectorWindow = new CitySelectorWindow(getActivity());
        mCitySelectorWindow.setOnCityChooseListener(new CitySelectorWindow.OnCityChooseListener() {
            @Override
            public void onCityChoose(final ProvinceInfo provinceInfo, final CityInfo cityInfo) {
                mTvCity.setText(String.format("%s %s", provinceInfo.getName(), cityInfo.getName()));
                LLApplication.reqUserRegister.setPostalProvince(provinceInfo.getId());
                LLApplication.reqUserRegister.setPostalCity(cityInfo.getId());
            }
        });
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvNext.setOnClickListener(this);
        mImgIdCardBack.setOnClickListener(this);
        mImgIdCardFront.setOnClickListener(this);
        mTvCity.setOnClickListener(this);
        WorksSizeCheckUtil worksSizeCheckUtil = new WorksSizeCheckUtil(mTvNext);
        worksSizeCheckUtil.addAllEditText(mEtSurname, mEtName, mEtIdCard, mEtMail, mTvCity, mEtAddress);
        worksSizeCheckUtil.setChangeListener(new WorksSizeCheckUtil.IEditTextChangeListener() {
            @Override
            public void textChange(boolean isHasContent) {
                mIsEditHasContent = isHasContent;
                LLApplication.reqUserRegister.setUserSurname(mEtSurname.getText().toString());
                LLApplication.reqUserRegister.setUserName(mEtName.getText().toString());
                LLApplication.reqUserRegister.setIdCard(mEtIdCard.getText().toString().trim());
                LLApplication.reqUserRegister.setMail(mEtMail.getText().toString().trim());
                LLApplication.reqUserRegister.setPostalAddress(mEtAddress.getText().toString());
                checkData();
            }
        });
        mRgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_female:
                        LLApplication.reqUserRegister.setMale(2);
                        break;
                    case R.id.rb_male:
                        LLApplication.reqUserRegister.setMale(1);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public void setPreRegisterInfo() {
        if (respPreRegister != null) {
            if (respPreRegister.getUserExtendInfo() == null || respPreRegister.getData() == null) {
                return;
            }
            PreRegisterExtendInfo registerExtendInfo = respPreRegister.getUserExtendInfo();
            PreRegisterInfo preRegisterInfo = respPreRegister.getData();
            mEtSurname.setText(registerExtendInfo.getUserSurname());
            mEtName.setText(registerExtendInfo.getUserName());
            mEtIdCard.setText(preRegisterInfo.getIdCard());
            if (preRegisterInfo.getMale() == 2) {
                mRgSex.check(R.id.rb_female);
            } else {
                preRegisterInfo.setMale(1);
                mRgSex.check(R.id.rb_male);
            }
            mEtMail.setText(preRegisterInfo.getMail());
            mEtAddress.setText(registerExtendInfo.getPostalAddress());
            mIdCardBackStr = preRegisterInfo.getIdCardBack();
            mIdCardFrontStr = preRegisterInfo.getIdCardFront();
            mCitySelectorWindow.setCityId(registerExtendInfo.getPostalProvince(),
                    registerExtendInfo.getPostalCity());

            if (!TextUtils.isEmpty(registerExtendInfo.getPostalProvince())) {
                VolleyRequestUtils.getInstance().getLazyEnum(this.toString(),
                        true, true, new ReqLazyEnum(), new INetWorkCallback() {
                            @Override
                            public void onSuccess(Object response) {
                                RespLazyEnum respUtilEnum = (RespLazyEnum) response;
                                mTvCity.setText(String.format("%s %s",
                                        respUtilEnum.getProvince().get(registerExtendInfo.getPostalProvince()),
                                        respUtilEnum.getCity().get(registerExtendInfo.getPostalCity())));
                            }

                            @Override
                            public void onFail(BaseResponse baseResponse) {
                            }
                        });
            }

            LLApplication.reqUserRegister.setUserSurname(registerExtendInfo.getUserSurname());
            LLApplication.reqUserRegister.setUserName(registerExtendInfo.getUserName());
            LLApplication.reqUserRegister.setIdCard(preRegisterInfo.getIdCard());
            LLApplication.reqUserRegister.setMale(preRegisterInfo.getMale());
            LLApplication.reqUserRegister.setMail(preRegisterInfo.getMail());
            LLApplication.reqUserRegister.setPostalAddress(registerExtendInfo.getPostalAddress());
            LLApplication.reqUserRegister.setPostalCity(registerExtendInfo.getPostalCity());
            LLApplication.reqUserRegister.setPostalProvince(registerExtendInfo.getPostalProvince());
            LLApplication.reqUserRegister.setIdCardBack(mIdCardBackStr);
            LLApplication.reqUserRegister.setIdCardFront(mIdCardFrontStr);

            if (!TextUtils.isEmpty(mIdCardBackStr)) {
                ShowImageUtils.showImageView(getActivity(), SystemConfig.IMAGE_BASE_URL + mIdCardBackStr,
                        SystemConfig.IMG_DEFAULT_BACKGROUND, mImgIdCardBack);
            }
            if (!TextUtils.isEmpty(mIdCardFrontStr)) {
                ShowImageUtils.showImageView(getActivity(), SystemConfig.IMAGE_BASE_URL + mIdCardFrontStr,
                        SystemConfig.IMG_DEFAULT_BACKGROUND, mImgIdCardFront);
            }
        }
    }

    private void checkData() {
        if (mIsEditHasContent && !TextUtils.isEmpty(mIdCardBackStr) && !TextUtils.isEmpty(mIdCardFrontStr)) {
            mTvNext.setEnabled(true);
            mTvNext.setClickable(true);
            mTvNext.setBackgroundResource(R.mipmap.login_btn);
        } else {
            mTvNext.setEnabled(false);
            mTvNext.setClickable(false);
            mTvNext.setBackgroundResource(R.drawable.bg_click_false);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_next:
                if (!new IDCard().verify(mEtIdCard.getText().toString())) {
                    showToast("请输入正确的身份证号码");
                    return;
                }
                if (!CommonUtils.isEmail(mEtMail.getText().toString())) {
                    showToast("请输入正确的邮箱");
                    return;
                }
                ReqVerifyID reqVerifyID = new ReqVerifyID();
                reqVerifyID.setIdCard(mEtIdCard.getText().toString());
                VolleyRequestUtils.getInstance().verifyIdCard(this.toString(), reqVerifyID, new INetWorkCallback() {
                    @Override
                    public void onSuccess(Object response) {
                        mOnNextClickListener.onNextClick();
                    }

                    @Override
                    public void onFail(BaseResponse baseResponse) {
                        showToast(baseResponse.getMsg());
                    }
                });
                break;
            case R.id.img_id_card_front:
                mImgIdCardFront.setTag(true);
                mImgIdCardBack.setTag(false);
                mBottomSheetDialog.showDialog();
                break;
            case R.id.img_id_card_back:
                mImgIdCardFront.setTag(false);
                mImgIdCardBack.setTag(true);
                mBottomSheetDialog.showDialog();
                break;
            case R.id.tv_risk_template:
                new ShowPictureDialog(getActivity(), R.mipmap.risk).show();
                break;
            case R.id.tv_city:
                if (mCitySelectorWindow == null) {
                    mCitySelectorWindow = new CitySelectorWindow(getActivity());
                    mCitySelectorWindow.setOnCityChooseListener(new CitySelectorWindow.OnCityChooseListener() {
                        @Override
                        public void onCityChoose(final ProvinceInfo provinceInfo, final CityInfo cityInfo) {
                            mTvCity.setText(String.format("%s %s", provinceInfo.getName(), cityInfo.getName()));
                            LLApplication.reqUserRegister.setPostalProvince(provinceInfo.getId());
                            LLApplication.reqUserRegister.setPostalCity(cityInfo.getId());
                        }
                    });
                }
                mCitySelectorWindow.showDialog();
                break;
            default:
                break;
        }
    }

    /**
     * 打开系统相机
     */
    private void openSysCamera() {
        File outPutFile = new File(ImageUtils.IMAGE_SAVE_PATH, "output.png");
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName()
                    + ".provider", outPutFile);
        } else {
            imageUri = Uri.fromFile(outPutFile);
        }
        //启动相机程序
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, SystemConfig.REQUEST_TAKE_PHOTO);
    }

    /**
     * 打开系统相册
     */
    private void openSysAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, SystemConfig.REQUEST_GALLERY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case SystemConfig.REQUEST_TAKE_PHOTO:
                    savePic(getImageUri());
                    break;
                case SystemConfig.REQUEST_GALLERY:
                    savePic(data.getData());
                    break;
                default:
                    break;
            }
        }
    }

    private void savePic(Uri imageUri) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            InputStream inputStream = getActivity().getContentResolver().openInputStream(imageUri);
            BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
            int height = options.outHeight;
            int width = options.outWidth;
            int sampleSize = 1;
            int max = Math.max(height, width);
            if (max > 769) {
                int nw = width / 2;
                int nh = height / 2;
                while ((nw / sampleSize) > 769 || (nh / sampleSize) > 769) {
                    sampleSize *= 2;
                }
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;
            Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri), null, options);
            String fileName = DateUtils.longToString(System.currentTimeMillis(), "yyyyMMddHHmmssSSS") +
                    (int) ((Math.random() * 9 + 1) * 100);
            String urlPath = ImageUtils.saveBitmap(getActivity(), bitmap, fileName + ".jpg");
            showLoadingDialog("上传中");
            UploadPic.uploadFileWithCompress(getActivity(), urlPath, new IUploadFileCallback() {
                @Override
                public void onProgress(int percent) {
                    Log.e("upload", percent + "");
                }

                @Override
                public void onData(Object output) {
                    dismissLoadingDialog();
                    MUploadFile mUploadFile = (MUploadFile) output;
                    if (mUploadFile.isResult()) {
                        showToast("上传成功");
                        setImageView(bitmap);
                        saveImagePath(mUploadFile);
                        checkData();
                    } else {
                        showToast("上传失败，请重试");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片裁剪Uri
     */
    private Uri getImageUri() {
        File outPutFile = new File(ImageUtils.IMAGE_SAVE_PATH, "output.png");
        Uri imageUri;
        int degree = ImageUtils.readPictureDegree(outPutFile.getPath());
        File file;
        if (degree != 0) {
            String path = ImageUtils.amendRotatePhoto(outPutFile.getPath(), degree, "output.png");
            file = new File(path);
        } else {
            file = outPutFile;
        }
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName()
                    + ".provider", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    private void setImageView(Bitmap bitmap) {
        if ((Boolean) mImgIdCardFront.getTag()) {
            mImgIdCardFront.setImageBitmap(bitmap);
        } else if ((Boolean) mImgIdCardBack.getTag()) {
            mImgIdCardBack.setImageBitmap(bitmap);
        }
    }

    private void saveImagePath(MUploadFile mUploadFile) {
        if ((Boolean) mImgIdCardFront.getTag()) {
            mIdCardFrontStr = mUploadFile.getUrl();
            LLApplication.reqUserRegister.setIdCardFront(mIdCardFrontStr);
        } else if ((Boolean) mImgIdCardBack.getTag()) {
            mIdCardBackStr = mUploadFile.getUrl();
            LLApplication.reqUserRegister.setIdCardBack(mIdCardBackStr);
        }
    }

}
